import {
  ComponentFactory,
  ComponentFactoryResolver,
  Directive,
  ElementRef,
  EventEmitter, Host,
  Input,
  OnDestroy,
  OnInit,
  Optional,
  Output,
  Renderer2, TemplateRef,
  ViewContainerRef
} from '@angular/core';
import { ApesNoAnimationDirective, ApesTSType, InputBoolean } from "@shared/apes/core";
import { ApesToolTipTrigger } from "@shared/apes/tooltip/apes-tooltip.definitions";

import { takeUntil } from 'rxjs/operators';

import { ApesPopConfirmComponent } from './apes-popconfirm.component';
import { ApesToolTipBaseDirective } from '@shared/apes/tooltip';

@Directive({
  selector: '[apes-popconfirm]',
  exportAs: 'apesPopconfirm',
  host: {
    '[class.apes-popover-open]': 'isToolTipComponentVisible'
  }
})
export class ApesPopConfirmDirective extends ApesToolTipBaseDirective implements OnInit {
  @Input('apesPopConfirmTitle') specificTitle: ApesTSType;
  @Input('apes-popconfirm') directiveNameTitle: ApesTSType | null;
  @Input('apesPopConfirmTrigger') specificTrigger: ApesToolTipTrigger;
  @Input('apesPopConfirmPlacement') specificPlacement: string;
  @Input() apesOkText: string;
  @Input() apesOkType: string;
  @Input() apesCancelText: string;
  @Input() apesIcon: string | TemplateRef<void>;
  @Input() @InputBoolean() apesCondition: boolean;

  @Input() apesTrigger: ApesToolTipTrigger = 'click';

  @Output() readonly apesOnCancel: EventEmitter<void> = new EventEmitter();
  @Output() readonly apesOnConfirm: EventEmitter<void> = new EventEmitter();

  componentFactory: ComponentFactory<ApesPopConfirmComponent> = this.resolver.resolveComponentFactory(ApesPopConfirmComponent);


  protected needProxyProperties = [
    'apesOverlayClassName',
    'apesOverlayStyle',
    'apesMouseEnterDelay',
    'apesMouseLeaveDelay',
    'apesVisible',
    'apesOkText',
    'apesOkType',
    'apesCancelText',
    'apesCondition',
    'apesIcon'
  ];

  constructor(
    elementRef: ElementRef,
    hostView: ViewContainerRef,
    resolver: ComponentFactoryResolver,
    renderer: Renderer2,
    @Optional() tooltip: ApesPopConfirmComponent,
    @Host() @Optional() public noAnimation?: ApesNoAnimationDirective
  ) {
    super(elementRef, hostView, resolver, renderer, tooltip, noAnimation);
  }

  /**
   * @override
   */
  protected createDynamicTooltipComponent(): void {
    super.createDynamicTooltipComponent();

    (this.tooltip as ApesPopConfirmComponent).apesOnCancel.pipe(takeUntil(this.$destroy)).subscribe(() => {
      this.apesOnCancel.emit();
    });
    (this.tooltip as ApesPopConfirmComponent).apesOnConfirm.pipe(takeUntil(this.$destroy)).subscribe(() => {
      this.apesOnConfirm.emit();
    });
  }
}
